package online.heycm.platform.web.cloud.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import online.heycm.platform.common.entity.constant.Constant;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign拦截器，设置请求头
 *
 * @author heycm
 * @since 2023/12/9 18:10
 */
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            setTraceId(template);
            return;
        }

        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String value = request.getHeader(name);
                if (StringUtils.hasText(value)) {
                    template.header(name, value);
                }
            }
        }

    }

    private void setTraceId(RequestTemplate template) {
        String traceId = MDC.get(Constant.TRACE_ID);
        String stepId = MDC.get(Constant.STEP_ID);
        if (StringUtils.hasText(traceId)) {
            template.header(Constant.TRACE_ID, traceId);
        }
        if (StringUtils.hasText(stepId)) {
            template.header(Constant.STEP_ID, stepId);
        }
    }
}
